<?php

/**
 * Class LoanAction
 * 我要借款
 */
class LoanAction extends BaseAction{

	protected function _initialize(){
		parent::_initialize();
		if(empty($this->user_session)){
			redirect(U('Login/index'));
		}
		$user_session = D('User')->get_user($this->user_session['uid']);
		$user_session['last'] = $this->user_session['last'];
		$this->user_session = $user_session;
		$this->assign('user_session',$this->user_session);

	}
	public function _empty(){
		$this->display();
	}

	//我要借款
	public function borrow(){
		//授信统计
		$pledges = D('Pledges')->where(array('uid'=>$this->user_session['uid']))->find();
		$this->assign('pledges',$pledges);
		$Db_id_card  = D('Id_card');
		$condition_uid = array('uid'=>$this->user_session['uid']);
		$result_idcard = $Db_id_card->field('`card_id`,`status`')->where($condition_uid)->find();

		$this->assign('result_idcard',$result_idcard);
		$Db_pledge_domain = D('Pledge_domain');
		$condition_pd['credit_status'] = 1; //已经授信域名
		$condition_pd['rz_status']     = 0; //0还没有开始融资的域名
		$condition_pd['uid'] = $this->user_session['uid'];
		$pledgelist = $Db_pledge_domain->field('`pid`,`uid`,`domain`,`credit_total`')->where($condition_pd)->select();
		$this->assign('pledgelist',$pledgelist);


		if(IS_POST){
			date_default_timezone_set('RPC');
			//file_put_contents('borrow_prepost.txt',print_r($_POST,true));
			$borrow_data['Amount']          = trim($_POST['Amount']);  //借款总额
			$borrow_data['needAmount']      = trim($_POST['Amount']);  //还需要投资金额第一次应该等于借款总额
			$borrow_data['pids']            = trim($_POST['pids'][0]);  //押质物(以逗号分隔押质域名id)
			$borrow_data['zlx']             = trim($_POST['zlx']);  //总利息
			$borrow_data['lx']              = trim($_POST['lx']);  //利息
			$borrow_data['myglf']           = trim($_POST['myglf']);  //管理费
			$borrow_data['zglf']            = trim($_POST['zglf']);  //总管理费用
			$borrow_data['myfk']            = trim($_POST['myfk']);  //每月还款
			$borrow_data['zhhk']            = trim($_POST['zhhk']);  //最后本金需还款
			$borrow_data['LoanCycleDay']    = trim($_POST['LoanCycleDay']);  //借款期限（天）
			$borrow_data['LoanCycleMonth']  = trim($_POST['LoanCycleMonth']);  //借款期限（月）
			$borrow_data['Rate']            = trim($_POST['Rate']);  //年利率
			$borrow_data['inlineOptions']   = trim($_POST['inlineOptions']);  //款方式 1 月还
			$borrow_data['ExpiredAt']       = trim($_POST['ExpiredAt']);  //截止日期
			$borrow_data['Amountdx']        = trim($_POST['Amountdx']);  //总贷款额 中文
			$borrow_data['status']          = 5;  //投标进度/状态
			$borrow_data['sh_status']       = 0;  //审核状态
			$borrow_data['Description']     = trim($_POST['Description']);  //
			$borrow_data['dname']           =  $this->user_session['nickname'];  // 贷款人
			$borrow_data['uid']             =  $this->user_session['uid'];  // 贷款人
			$borrow_data['borrowstatus']    =  $this->user_session['uid'];  // 贷款人(借入人)
			$borrow_data['did']             = 'D'.date('ymdHis').'u'.$this->user_session['uid'];  // 贷款编号
			$borrow_data['addTime']         = time();

			if($borrow_data['LoanCycleDay'] > 0){ //天
				//$borrow_data['repayDate']  = date('Y-m-d',strtotime("{$borrow_data['ExpiredAt']}  + {$borrow_data['LoanCycleDay']} day"));
				$borrow_data['periods'] = 1; //总还款期数
			}else if($borrow_data['LoanCycleMonth'] > 0){ //月
				//每个月按 30 天来计算
				$days = $borrow_data['LoanCycleMonth'] * 30;
				//$borrow_data['repayDate']  = date('Y-m-d',strtotime("{$borrow_data['ExpiredAt']}  + $days day"));
				$borrow_data['periods'] = trim($_POST['LoanCycleMonth']);  //总还款期数
			}

			if($borrow_data['Amount'] == ''){
				echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'借款总额不可以为空'));exit;
			}
			if( empty($borrow_data['zlx']) ||
			    empty($borrow_data['lx']) ||
				empty($borrow_data['myglf']) ||
				empty($borrow_data['zglf']) ||
				empty($borrow_data['zhhk']) ||
				empty($borrow_data['Rate'])
			){
				echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'请检查所填写的项是否为空！'));exit;
			}

			//只要设置了天，月则为0
			if(!empty($borrow_data['LoanCycleDay'])||$borrow_data['LoanCycleDay'] != 0){
				if(intval($borrow_data['LoanCycleDay']) == 7){
					//7天标 最低利率不得低于16%
					if($borrow_data['Rate'] < 16){
						echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'7天标 最低利率不得低于16%'));exit;
					}
				}
				if(intval($borrow_data['LoanCycleDay']) == 15){
					//15天标 最低利率不得低于14%
					if($borrow_data['Rate'] < 14){
						echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'15天标 最低利率不得低于14%'));exit;
					}
				}
				$borrow_data['LoanCycleMonth'] = 0;
			}
			if((empty($borrow_data['ExpiredAt'])) || (strtotime(date('Y-m-d',time())) > strtotime($borrow_data['ExpiredAt']))){
				echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'截止日期不可为空或者小于当前时间'));exit;
			}

			//未过审核之前，也先扣除授信【后台审核通过之后确认授信】
			if(D('Borrows')->data($borrow_data)->add()){
				//未过审核之前，也先扣除授信【后台审核通过之后确认授信】
				$Db_pledges = 	D('Pledges');
				$Db_pledges->where('`uid`='.$this->user_session['uid'])->setInc('brrowing_total',$borrow_data['Amount']);//增加 借款总额
				$Db_pledges->where('`uid`='.$this->user_session['uid'])->setDec('credit_now',$borrow_data['Amount']);//减去 可用信额
				$wherepid['pid'] = array('in',$borrow_data['pids']);
				D('Pledge_domain')->where($wherepid)->setField('rz_status',5);//申请融资中，还未审核通过
				//file_put_contents('pledge.log',D('Pledge_domain')->getLastSql());
				unset($_POST);
				echo json_encode(array('error'=>0,'title'=>'恭喜，提交成功','msg'=>'请耐心等待审核，审核通过之后即可发布！'));exit;
			}else{
				echo json_encode(array('error'=>-1,'title'=>'出错了','msg'=>'提交失败，请重新提交！'));exit;
			}

		}

		$this->display();
	}

	//质押管理
	public function pledge(){
		$Db_id_card  = D('Id_card');
		$condition_uid = array('uid'=>$this->user_session['uid']);
		$result_idcard = $Db_id_card->field('`card_id`,`status`')->where($condition_uid)->find();
		$this->assign('result_idcard',$result_idcard);
		$Db_pledge_domain = D('Pledge_domain');
		if(IS_POST){
			$keyword = strtolower(trim($_POST['keyword']));
			$get_str =  array();
			$get_str = explode('.',$keyword);
			if(count($get_str) > 0|| $keyword !=''){
				 if(!empty($get_str[1])){
					 $condition_uid['domain'] = $keyword ;
				 }else{
					 $condition_uid['domain'] = array('like','%'.$get_str[0].'%');
				 }
			}
		}
		$pledgelist = $Db_pledge_domain->where($condition_uid)->order('`apply_time` DESC')->select();
		$this->assign('pledgelist',$pledgelist);

		$this->display();
	}

	//借入列表
	public function borrowList(){
		$Db_borrows = D('Borrows');
		$Db_pledge_domain = D('Pledge_domain');
		$conditions['uid'] = $this->user_session['uid'];
		$status = intval($_GET['state']) ?intval($_GET['state']):0;
		$this->assign('state',$status);
		switch($status){
			case 1:
				$conditions['status'] = '1';
				break;
			case 2:
				$conditions['status'] = '2';
				break;
			case 3:
				$conditions['status'] = '3';
				break;
			case 4:
				$conditions['status'] = '4';
				break;
		}
		$borrowsList = $Db_borrows->where($conditions)->order('`bid` DESC')->select();
		$start_date = date('Y-m-d',time());

		foreach($borrowsList as $key=>$val){
			$borrowsList[$key]['surplus_date'] = getBetweenTwoDate($start_date,$val['ExpiredAt']);
		}

		$this->assign('borrowsList',$borrowsList);
		$this->display();

	}

	//一次性还款（无违约金）
	public function borrowoption(){
		if($this->isAjax()){
			$_POST['bid'] = intval($_POST['id']) ? intval($_POST['id']) :0;
			$_POST['type'] = intval($_POST['type']) ? intval($_POST['type']) :0;
			if(($_POST['bid'] > 0) && $_POST['type'] == 1){
				$Db_borrows =  D('Borrows');
				// 7 审核失败的才可以删除,
				if($Db_borrows->where(array('bid'=>  intval($_POST['bid']),'uid'=>$this->user_session['uid'],'status'=>'7'))->delete()){
					exit(json_encode(array('error'=>0,'msg'=>'删除成功','isreload'=>0)));
				}  else {
					exit(json_encode(array('error'=>1,'msg'=>'删除失败','isreload'=>0)));
				}
			}

			if(($_POST['bid'] >0) && $_POST['type'] == 2){
				date_default_timezone_set('PRC');
				/**
				 * 一次还清欠款  开始
				 *借款 10000 ，总利息 100  总管理费 50
				 *  一次还清欠款 10150 = 10000 + 100  + 50
				 * 真实应该还款总金额 = （借款 10000  + 总利息 100 + 总管理费 50) - 已还金额 - 已还总管理费
				 */
				$Db_loan_trade_pass = D('Loan_trade_pass');
				$trade_password =trim($_POST['inputVal']);
				$trade_pass['trade_password'] = md5($trade_password);
				$trade_pass['uid']            = $this->user_session['uid'];
				$is_set_pass = $Db_loan_trade_pass->where($trade_pass)->find();
				if(empty($is_set_pass)){
					exit(json_encode(array('error'=>1,'msg'=>'交易密码错误！')));
				}

				$Db_payment_history = D('Payment_history');
				$Db_borrows     = D('Borrows');
				$Db_pledges     = D('Pledges');
				$Db_investment  = D('Investment');
				$Db_user        = D('User');
				$borrows_con['bid'] = $_POST['bid'];
				$borrows =  $Db_borrows->where($borrows_con)->find();
				if(!empty($borrows)){

					$Db_user_money_list = D('User_money_list');
					if($borrows['LoanCycleDay'] > 0){ //天
						$date_is_overdue = date('Y-m-d',strtotime("{$borrows['repayDate']}  + {$borrows['LoanCycleDay']} day"));
						$history_loancycle = $borrows['LoanCycleDay'];
					}else if($borrows['LoanCycleMonth'] > 0){ //月
						//每个月按 30 天来计算
						$days = $borrows['LoanCycleMonth'] * 30;
						$date_is_overdue = date('Y-m-d',strtotime("{$borrows['repayDate']}  + $days day"));
						//$date_is_overdue = date('Y-m-d',strtotime("{$borrows['repayDate']}  + {$borrows['LoanCycleMonth']} month"));
						$history_loancycle = $borrows['LoanCycleMonth'] * 30;
					}

					//真实应该还款总金额 = （借款 10000  + 总利息 100 + 总管理费 50) - 已还金额 - 已还总管理费
					$yghkze = ($borrows['Amount'] + $borrows['zlx'] + $borrows['zglf']) - $borrows['yh_menory'] - $borrows['yh_zglfees'];
					//echo "真实应该还款总金额:{$yghkze}<br/>";
					//判断个人账号里是否有足够的可用金额进行还款
					$user_now_menory = $Db_user->where('`uid`='.$this->user_session['uid'])->getField('now_money');
					//echo "账户现在可以用的总金额:{$user_now_menory}<br/>";
					if($yghkze > $user_now_menory){
						exit(json_encode(array('error'=>1,'msg'=>'抱歉您的账户余额不足，请及时充值，及时还款，保证您的良好信用！','isreload'=>1)));
					}
					if(nowTimeMax($date_is_overdue)){
						//TODO
						/**
						 * 借款逾期了怎么办？
						1、借款期内，如果借入者未在规定的时间偿还借款利息和管理费用，诚借平台将加收所欠利息的0.5%/日作为违约金；
						2、借款合同到期后，如果借入者未能按时偿还本金、利息和管理费用，诚借平台将加收所欠款项的0.5%/日作为违约金，另需与诚借平台客服联系，约定还款日期，诚借平台将保留对质押物依法处分用以清偿债务的权利。
						如果逾期还款，诚借平台有权根据具体情况将用户列入不良信用客户，诚借平台强烈呼吁借款用户尽量避免逾期还款，一旦发生逾期请尽快还清贷款。
						 */

						$pledges_save['is_overdue'] = 1; //逾期
						$payment_history_add['yq_menory'] = $yghkze + $borrows['breachMoney'];  //逾期金额 = 应还总额 + 违约金
						$payment_history_add['yq_time'] = time();  //逾期还款时间
						$payment_history_add['status'] = 2;

						$user_now_menory_list_fk['type'] = 23;   //逾期罚款金额
						$user_now_menory_list_fk['uid']  = $this->user_session['uid'];
						$user_now_menory_list_fk['money']  =$borrows['breachMoney'];
						$user_now_menory_list_fk['now_money']  =$user_now_menory - $borrows['breachMoney'];
						$user_now_menory_list_fk['time']  = time();
						$user_now_menory_list_fk['typeofs']  = 1;
						$user_now_menory_list_fk['desc']  = '逾期罚款';
						$Db_user_money_list->add($user_now_menory_list_fk);
						//$user_now_menory_bj['type'] = 19; //本金扣款


					}
					$payment_history_add['uid'] =  $this->user_session['uid'];//当前还贷人uid
					$payment_history_add['bid'] =  $borrows['bid'];//当前还贷bid
					$payment_history_add['LoanCycle'] = $history_loancycle;//还款期数（按天）
					$payment_history_add['yh_time'] = strtotime($borrows['repayDate']);//应还时间 = 上次一次还款时间 + 【可能有BUG】
					$payment_history_add['hk_time'] = time();//还款时间
					$payment_history_add['status'] = 1;//已经还清
					$payment_history_add['hk_benxi'] = $borrows['Amount'] + $borrows['zlx'];//还款本息
					$payment_history_add['yh_glfees'] = $borrows['zglf'];//已还总管理费

					//-----------------------------------------

					//---------------------------------------------
					if($Db_user->where('`uid`='.$this->user_session['uid'])->setDec('now_money',$yghkze)){ //扣除金额

						$Db_payment_history->add($payment_history_add);
						$Db_pledges->where('`uid`='.$this->user_session['uid'])->setDec('stay_total',$yghkze); // 减去待还款总额
						/**
						 * * 已还贷款本金款额 = （借款 10000  + 总利息 100 )
						 * 已还总管理费  = 总管理费
						 */
						$borrows_save['yh_menory'] = $borrows['Amount'] + $borrows['zlx']; //已还贷款本金款额
						$borrows_save['yh_zglfees'] = $borrows['zglf'];   //已还总管理费
						$borrows_save['status']   = 3; //还款结束
						$borrows_save_condition['uid'] = $this->user_session['uid'];
						$borrows_save_condition['bid'] = $borrows['bid'];
						$Db_borrows->where($borrows_save_condition)->data($borrows_save)->save();
						//找出对应的投资人 进行打款 【需要判断已经收到的款】
						$inves_uids = explode(',',$borrows['inves_uids']);
						foreach($inves_uids as $thisuid){
							$investment_con['uid'] =$thisuid;
							$investment_con['did'] = $borrows['bid'];
							$investment = $Db_investment->where($investment_con)->find();
							//dump($investment);
							//已收本息 = 投资金额 + 每期利息收益 * 期数 (7天,15天,30 天 算一期  ； 2个月-12个月 一个月一期)
							$duoshaoqishu = $investment['LoanCycle'] / 30;
							if($duoshaoqishu <= 1){
								$duoshaoqishu = 1; //7天,15天,30 天 算一期
							}
							$sh_benjin = $investment['Amount'] + $investment['nsy'] * $duoshaoqishu;
							$investment_save['TR_principal'] = $sh_benjin;
							$investment_save['status']       = 4;
							$Db_investment->where($investment_con)->data($investment_save)->save();
							//投资人 资金收回 ,解冻投资金额
							$Db_user->where('`uid`='.$thisuid)->setInc('now_money',$sh_benjin);
							$Db_user->where('`uid`='.$thisuid)->setDec('freeze_money',$investment['Amount']);
							//投资人的理财荣誉
							$thisuid_lend_total = $Db_pledges->where('`uid`='.$thisuid)->getField('lend_total');
							if(($thisuid_lend_total  >= 5000000) && ($thisuid_lend_total < 10000000) ){
								$pledges_save_this['honor'] = 2;
								$Db_pledges->where('`uid`='.$thisuid)->data($pledges_save_this)->save();
							}elseif($thisuid_lend_total >= 10000000){
								$pledges_save_this['honor'] = 3;
								$Db_pledges->where('`uid`='.$thisuid)->data($pledges_save_this)->save();
							}
						}
						//借款人的理财荣誉
						$jk_lend_total = $Db_pledges->where('`uid`='.$this->user_session['uid'])->getField('lend_total');
						if(($jk_lend_total  >= 5000000) && ($jk_lend_total < 10000000) ){
							$pledges_save['honor'] = 2;
							$Db_pledges->where('`uid`='.$thisuid)->data($pledges_save)->save();
						}elseif($jk_lend_total >= 10000000){
							$pledges_save['honor'] = 3;
							$Db_pledges->where('`uid`='.$thisuid)->data($pledges_save)->save();
						}
						exit(json_encode(array('error'=>0,'msg'=>"恭喜，您已经还清【贷款号：{$borrows['did']}】的欠款！",'isreload'=>1)));
					}else{
						exit(json_encode(array('error'=>1,'msg'=>'划款系统出现故障，划款失败，请刷新页面重新还款！','isreload'=>1)));
					}
				}
			}/** * 一次还清欠款  结束 */

		}else{
			exit();
		}
	}


	//按月还款
	public function month_borrowo(){
		$bid  = intval($_POST['id'])   ? intval($_POST['id'])   : 0;
		$type = intval($_POST['type']) ? intval($_POST['type']) : 0;
		if($bid < 0 || $type < 0){
			exit(json_encode(array('error'=>-1,'msg'=>'你已经访问到银河系了！')));
		}
		if($bid && $type == 2){
			$Db_borrows     = D('Borrows');
			$borrows_con['bid'] = $bid;
			$borrows_con['status'] = 2;
			$borrows_con['uid'] = $this->user_session['uid'];
			$borrows =  $Db_borrows->where($borrows_con)->find();
			if(empty($borrows)){
				exit(json_encode(array('error'=>-1,'msg'=>'木有该记录，你已经访问到银河系了！')));
			}
			$Db_payment_history = D('Payment_history');
			$Db_pledges     = D('Pledges');
			$Db_investment  = D('Investment');
			$Db_user        = D('User');
			if($borrows['LoanCycleDay'] > 0){ //天
				//$date_is_overdue = date('Y-m-d',strtotime("{$borrows['repayDate']}  + {$borrows['LoanCycleDay']} day"));
				$history_loancycle = $borrows['LoanCycleDay'];
			}else if($borrows['LoanCycleMonth'] > 0){ //月
				//$date_is_overdue = date('Y-m-d',strtotime("{$borrows['repayDate']}  + {$borrows['LoanCycleMonth']} month"));
				$history_loancycle = $borrows['LoanCycleMonth'] * 30;
			}
			//判断个人账号里是否有足够的可用金额进行还款
			$user_now_menory = $Db_user->where('`uid`='.$this->user_session['uid'])->getField('now_money');
			$is_last_periods = $borrows['periods'] - $borrows['periodsed']; //总还期数 - 已还期数
			$not_last_repayDate = false;
			if($is_last_periods == 1){
				//（7,14,30 算一期）最后一期了
				//本次应该还款总额  = 总利息：￥13800.00 ,总管理费：￥6900.00 ) + 最后本金需还款：50000.00
				$yghkze = $borrows['zlx'] +$borrows['zglf'] + $borrows['zhhk'];
				if($yghkze > $user_now_menory){
					exit(json_encode(array('error'=>1,'msg'=>'抱歉您的账户余额不足，请及时充值，及时还款，保证您的良好信用！','isreload'=>1)));
				}
				$not_last_repayDate = false;
				$borrows_save_data['status'] = 3; //状态修改为还款结束
				$borrows_save_data['periodsed'] =  $borrows['periods']; //已还期数

			}else{
				//只还 利息，不用还本金
				//本次应该还款总额  = 每月还款：￥20700.00 (利息：￥13800.00 ,管理费：￥6900.00 )
				$yghkze = $borrows['myfk'];
				if($yghkze > $user_now_menory){
					exit(json_encode(array('error'=>1,'msg'=>'抱歉您的账户余额不足，请及时充值，及时还款，保证您的良好信用！','isreload'=>1)));
				}
				$not_last_repayDate = true; //还有下一次还款时间

				if($borrows['NextRepayDate'] != '0000-00-00'){
					//下一次应还时间；NextRepayDate = 上一次还款   + 30天
					$nextRepayDate = $borrows['NextRepayDate'];
				}else{
					//下一次应还时间；NextRepayDate = 第一次还款时间  + 30天
					$nextRepayDate = $borrows['repayDate'];
				}
				$borrows_save_data['NextRepayDate']  = date('Y-m-d',strtotime("$nextRepayDate  + 30 day"));
				$borrows_save_data['periodsed'] =  $borrows['periodsed'] + 1; //已还期数 +1
			}
//			echo "这次应还时间：{$borrows['repayDate']} <br/>";
//			echo "下一次还款时间".$borrows_save_data['NextRepayDate'];

//***********************************************************************************************

//***********************************************************************************************

			//扣除还款人的资金
			$isok = $Db_user->where('`uid`='.$this->user_session['uid'])->setDec('now_money',$yghkze);
			//减去待还总额
			$is_ok_two = $Db_pledges->where('`uid`='.$this->user_session['uid'])->setDec('stay_total',$yghkze);
			if($isok){  //还款成功
				$borrows_setInc_con['uid'] = $this->user_session['uid'];
				$borrows_setInc_con['bid'] = $borrows['bid'];
				if($not_last_repayDate){  //还不是最后一次还款
					$Db_borrows->where($borrows_setInc_con)->setInc('yh_menory',$borrows['lx']);//增加已还贷款本金款额 = 利息
					$Db_borrows->where($borrows_setInc_con)->setInc('yh_zglfees',$borrows['myglf']);//增加已还总管理费 = 管理费
				}else{
					$Db_borrows->where($borrows_setInc_con)->setInc('yh_menory',$borrows['lx'] + $borrows['zhhk']);//增加已还贷款本金款额 = 利息 + 最后本金需还款
					$Db_borrows->where($borrows_setInc_con)->setInc('yh_zglfees',$borrows['myglf']);//增加已还总管理费 = 管理费
				}
				$Db_borrows->where($borrows_setInc_con)->save($borrows_save_data);

				//找出谁投资了，进行按每期收益还款
				$whos_investment_arr =  explode(',',$borrows['inves_uids']);
				foreach($whos_investment_arr as $investment_id){
					$investment_con['uid'] =$investment_id;
					$investment_con['did'] = $borrows['bid'];

					$investments = $Db_investment->where($investment_con)->select(); // select一个人投资多次

					foreach($investments  as $investment ){
						$investment_save_con['uid'] =$investment_id;
						$investment_save_con['did'] = $borrows['bid'];
						$investment_save_con['iid'] = $investment['iid'];
						if($not_last_repayDate){
							//投资人 已收本息  = 已收本息 + 每期利息收益
 	                        $sh_benjin = $investment['TR_principal'] + $investment['nsy'];
							$investment_save['TR_principal'] = number_format($sh_benjin,2);
							//$Db_investment->where($investment_save_con)->setInc('TR_principal',$investment['nsy']);
							$investment_save['status']       = 2; //2收款中
							$Db_investment->where($investment_save_con)->data($investment_save)->save();
						}else{
							//投资人 已收本息  = 投资总金额 + 每期利息收益 * 期数
							$sh_benjin = $investment['Amount'] + $investment['nsy'] * $borrows['periods'];
							$investment_save['TR_principal'] = number_format($sh_benjin,2);
							$investment_save['status']       = 4; //4 借款收回完成
							$Db_investment->where($investment_save_con)->data($investment_save)->save();
						}

	//file_put_contents('IID-'.$investment['iid'].'-UID-'.$investment_id.'--'.time().'investment_save.log',print_r($investment_save,true));

					}



					//投资人 资金收回 ,解冻投资金额
					$Db_user->where('`uid`='.$investment_id)->setInc('now_money',$sh_benjin);
					$Db_user->where('`uid`='.$investment_id)->setDec('freeze_money',$investment['Amount']);
					//投资人的理财荣誉
					$thisuid_lend_total = $Db_pledges->where('`uid`='.$investment_id)->getField('lend_total');
					if(($thisuid_lend_total  >= 5000000) && ($thisuid_lend_total < 10000000) ){
						$pledges_save_this['honor'] = 2;
						$Db_pledges->where('`uid`='.$investment_id)->data($pledges_save_this)->save();
					}elseif($thisuid_lend_total >= 10000000){
						$pledges_save_this['honor'] = 3;
						$Db_pledges->where('`uid`='.$investment_id)->data($pledges_save_this)->save();
					}
				}

				//借款人的理财荣誉
				$jk_lend_total = $Db_pledges->where('`uid`='.$this->user_session['uid'])->getField('lend_total');
				if(($jk_lend_total  >= 5000000) && ($jk_lend_total < 10000000) ){
					$pledges_save['honor'] = 2;
					$Db_pledges->where('`uid`='.$investment_id)->data($pledges_save)->save();
				}elseif($jk_lend_total >= 10000000){
					$pledges_save['honor'] = 3;
					$Db_pledges->where('`uid`='.$investment_id)->data($pledges_save)->save();
				}

				//记录还款记录
				$payment_history_add['uid'] =  $this->user_session['uid'];//当前还贷人uid
				$payment_history_add['bid'] =  $borrows['bid'];//当前还贷bid
				$payment_history_add['LoanCycle'] = $borrows_save_data['periodsed'];//还款期数
				if($not_last_repayDate){ //还不是最后一次还款时间，就要重新计算下一次还款时间
					$payment_history_add['yh_time'] = $borrows['repayDate'];
					$payment_history_add['status'] = 0;//正在还款
					//$本次应该还款总额  = 每月还款：￥20700.00 (利息：￥13800.00 ,管理费：￥6900.00 )
					//还款本息 =
					$payment_history_add['hk_benxi'] = $borrows['myfk'];//还款本息 = 每月还款
					$payment_history_add['yh_glfees'] = $borrows['myglf'];//已还管理费
				}else{  //最后一次还款
					$payment_history_add['status'] = 1;//已经还清
					//$本次应该还款总额  = 总利息：￥13800.00 ,+ 最后本金需还款：50000.00
					$payment_history_add['hk_benxi'] = $borrows['zlx']  + $borrows['zhhk'];//还款本息
					$payment_history_add['yh_glfees'] = $borrows['zglf'];//已还管理费 =总管理费
				}
				$payment_history_add['hk_time'] = time();//本次还款时间
				$Db_payment_history->add($payment_history_add);

				exit(json_encode(array('error'=>0,'msg'=>'恭喜本次还款成功，请继续保持良好的借贷信用 :)')));
			}else{
				exit(json_encode(array('error'=>-1,'msg'=>'还款失败，请重新还款！')));
			}

		}
		//exit(json_encode(array('error'=>-1,'msg'=>'你已经访问到银河系了！')));

	}


	//申请授信
	public function creditApply(){
		if(IS_POST){
			$okArr = array();
			$errorArr = array();

			if(empty($_POST['domain']) || $_POST['domain'] == '域名一行一个，请输入顶级域名') {unset($_POST); $this->error('请填写至少一个域名');}
			$postDomainTmpArr = explode(PHP_EOL,$_POST['domain']);
			$postDomainArr = array();
			foreach($postDomainTmpArr as $value){
				$value = trim($value);
				if(!empty($value)){
					$postDomainArr[] = trim($value);
				}
			}

			//找出系统支持的后缀列表
			$suffix_list = D('Domain_suffix')->field('`suffix`')->where(array('status'=>'1'))->select();
			$suffixArr = array();
			foreach($suffix_list as $value){
				$suffixArr[] = $value['suffix'];
			}
			foreach($postDomainArr as $key=>$value){
				if(substr_count($value,'.') == 0){
					$errorArr[] = array('domain'=>$value,'msg'=>'域名不合法');
					continue;
				}
				$tmpDomain = str_replace($suffixArr,'',$value);
				if(empty($tmpDomain)){
					$errorArr[] = array('domain'=>$value,'msg'=>'域名不合法');
					continue;
				}
				if($tmpDomain == $value){
					$errorArr[] = array('domain'=>$value,'msg'=>'域名后缀不合法');
					continue;
				}
				if(substr_count($tmpDomain,'.') > 0){
					$errorArr[] = array('domain'=>$value,'msg'=>'请填写顶级域名');
					continue;
				}
				if(!preg_match('/^\w+$/',$tmpDomain)){
					$errorArr[] = array('domain'=>$value,'msg'=>'目前只支持英文域名');
					continue;
				}
				$okArr[] = strtolower($value);
			}

			$Db_pledge_domain = D('Pledge_domain');
			$pd_data['uid'] = $this->user_session['uid'];
			$pd_data['credit_status'] = '0';
			$pd_data['apply_time'] = $_SERVER['REQUEST_TIME'];
			$pd_data['pledge_status'] = '0';
			$pd_data['rz_status'] = '0';
			$pd_data['is_check'] = '0';
			foreach($okArr as $key=>$value){
				$pd_data['domain'] = $value;
				if($Db_pledge_domain->where(array('domain'=>$value,'uid'=>$this->user_session['uid']))->find()){
					unset($okArr[$key]);
					$errorArr[] = array('domain'=>$value,'msg'=>'已添加过该域名');
					continue;
				}
				if($Db_pledge_domain->data($pd_data)->add()){
					//redirect(U('Loan/pledge'));
				}else{
					unset($okArr[$key]);
					$errorArr[] = array('domain'=>$value,'msg'=>'添加失败，请重试');
					continue;
				}
			}
			if(empty($okArr)) unset($okArr);
			$this->assign('okArr',$okArr);

			if(empty($errorArr)) unset($errorArr);
			$this->assign('errorArr',$errorArr);

		}
		$this->display();
	}

	public function checkwithdomain(){
		$Db_pledge_domain = D('Pledge_domain');
		$conditionDomainCheck['uid'] = $this->user_session['uid'];
		$conditionDomainCheck['pid'] = intval($_POST['id']);
		$nowDomain = $Db_pledge_domain->field(true)->where($conditionDomainCheck)->find();

		if(empty($nowDomain)){
			$this->error('当前域名不存在');
		}
		if($_POST['type'] == 0){
			import('@.ORG.NewWhois');
			$newInfo = new NewWhois();
			$whoisResult = $newInfo->getNewWhois($nowDomain['domain']);

//			import('@.ORG.whois');
//			$whoisClass = new whois();
//			$whoisResult = $whoisClass->getWhois($nowDomain['domain']);
			if(empty($whoisResult) || empty($whoisResult['registrarEmail'])){
				$this->error('当前域名没找到whois信息,请联系客服');
			}
			// dump($whoisResult);
			if(D('Domain_whoisemail')->where(array('uid'=>$this->user_session['uid'],'email'=>$whoisResult['registrarEmail'],'is_check'=>'1'))->find()){

				if($Db_pledge_domain->where(array('uid'=>$this->user_session['uid'],'pid'=>intval($_POST['id'])))->data(array('is_check'=>'1'))
					->save()){
					//$this->success('验证成功');
					exit(json_encode(array('error'=>0,'msg'=>'验证成功','isreload'=>0)));
				}else{
					//$this->error('验证失败，请重试');
					exit(json_encode(array('error'=>1,'msg'=>'验证失败','isreload'=>0)));
				}
			}else{
				//$this->error('该whois对应的邮箱不是您的邮箱，请添加邮箱');
				//exit(json_encode(array('error'=>1)));
				exit(json_encode(array('error'=>1,'msg'=>'该whois对应的邮箱不是您的邮箱，请添加邮箱','isreload'=>0)));
			}
		}  else if($_POST['type'] == 1){
			if($Db_pledge_domain->where(array('pid'=>  intval($_POST['id']),'uid'=>  $this->user_session['uid']))->delete()){
				//echo 1;
				exit(json_encode(array('error'=>0,'msg'=>'删除成功','isreload'=>1)));
			}  else {
				exit(json_encode(array('error'=>1,'msg'=>'删除失败','isreload'=>0)));
			}
		}
	}

	// 最近一个月需要还款的贷款列表
	public function paymentHistory(){
		$Db_borrows       = D('Borrows');
		$conditions['uid'] = $this->user_session['uid'];

		$state = intval($_GET['state']) ? intval($_GET['state']) : 0;
		$conditions['status'] = 2;
		if($state == 1){
			$conditions['breachMoney'] = array('neq',''); //还款逾期
		}
		$this->assign('state',$state);
		$borrowsList = $Db_borrows->where($conditions)->select();
		//echo $Db_borrows->getLastSql();
		//dump($borrowsList);
		$now_borrows = array();
		foreach($borrowsList as $key=>$borrows){
			$start_date = date('Y-m-d',time());
			$end_date = $borrows['NextRepayDate'];
			$get_borrow_date = getBetweenTwoDate($start_date, $end_date);
			if($get_borrow_date >=0 && $get_borrow_date <=30 ) {
				//echo "bid={$borrows['bid']}计算现在{$start_date} 到 应还时间：{$end_date}，相差{$get_borrow_date}天（日）<br/>";
				$now_borrows[$key] = $borrows;
				$now_borrows[$key]['surplus_date']  = $get_borrow_date;
			}


			if($get_borrow_date < 0 && $state == 1){
				//逾期
				$now_borrows[$key] = $borrows;
				$now_borrows[$key]['surplus_date']  = abs($get_borrow_date);
				$this->assign('yuqi',1);
			}
		}

		$this->assign('now_borrows',$now_borrows);
		//dump($now_borrows);
		$this->display();
	}

	public function getBreachs(){
		if(IS_POST){
			$bid = intval($_POST['id']) ?  intval($_POST['id']) : 0;
			if($bid > 0){
				$condition['uid'] =  $this->user_session['uid'];
				$condition['bid'] = $bid;
				$Db_breachs = D('Breachs');
				$breachsList = $Db_breachs->where($condition)->select();
				if(empty($breachsList)){
					$return = array('error'=>-1,'title'=>'获取信息失败','msg'=>'系统无法找到该条记录！');
					$this->ajaxReturn($return);
				}
				$table = '';
				$table .= '<div class="table-responsive">
					 	<table class=" table table-bordered table-striped table-hover">
							<thead>
						<tr>
							<th>合同ID</th>
							<th>违约金额</th>
							<th>违约时间</th>
							<th>违约天数</th>
							<th>违约类型</th>
						</tr>
						</thead>
						<tbody class="text-center">';

				foreach($breachsList as $val){
					$total += $val['breachMoney'];
					switch($val['status']){
						case 1:
							$status = '借款期内';
							break;
						case 2:
							$status = '合同到期后';
							break;
					}
					$table .= "<tr>
							<td>{$val['bid']}</td>
							<td>￥{$val['breachMoney']}</td>
							<td>{$val['breachTiem']}</td>
							<td>{$val['breachDays']}</td>
							<td>$status</td>
							</tr>";
				}
				$chiness_total = number2Chinese($total);
				$table .= "<tr><td>累计违约：</td> <td colspan='2'>$chiness_total</td>	 <td colspan='2'>￥$total</td></tr>";

				$table .= '</tbody></table></div>';
				$return = array('error'=>0,'title'=>'贷款违约详细信息列表','msg'=>'成功','htmldata'=>$table);
				$this->ajaxReturn($return);
			}else{
				$return = array('error'=>-1,'title'=>'获取信息失败','msg'=>'系统无法找到该条记录！');
				$this->ajaxReturn($return);
			}
		}
	}



}